//
//  RTUserAcountViewModel.swift
//  Weibo
//
//  Created by Brisinga on 16/3/5.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

class RTUserAcountViewModel: NSObject {
    
    
    // 判断用户是否登录
    var userLogin: Bool {
        
        if self.access_token != nil && !self.isExpiresIn {
            
            return true
            
        }
        
            return false
        
    }
    
    //判断token值是否过期
    var isExpiresIn: Bool {
        
        if NSDate().compare(acount!.expires_Date!) == .OrderedAscending {
            
            return false
        }else {
            
            return true
        }
    }
    
    // token值
    var access_token: String? {
        
        return acount?.access_token
    }
    
    // 模型
    var acount: RTUserAcount? {
        
        didSet{
        
            print("外界给我赋值了")
        }
    }
    
    
    // 创建单例
    static let sharedAccountViewModel: RTUserAcountViewModel = {
        
        let sharedAccountViewModel = RTUserAcountViewModel()
        
        sharedAccountViewModel.acount = sharedAccountViewModel.loadUserAcount()
        
        return sharedAccountViewModel
    }()
    
    
    func loadAccessToken(code: String,callBack:(isSuccess: Bool)->()) {
        
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        
        /**
         必选	类型及范围	说明
         client_id	true	string	申请应用时分配的AppKey。
         client_secret	true	string	申请应用时分配的AppSecret。
         grant_type	true	string	请求的类型，填写authorization_code
         
         grant_type为authorization_code时
         必选	类型及范围	说明
         code	true	string	调用authorize获得的code值。
         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
         */
        
        let parameters = [
            
            "client_id":WB_APPKEY,
            "client_secret":WB_APPSECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_REDIRECT_URI
        ]
        
        
        HMNetworkTools.sharedTools.requst(.POST, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                
                print(error)
                callBack(isSuccess: false)
                return
            }
            
            print(responseObject)
            
            // 字典转模型
            let userAcount = RTUserAcount(dict: responseObject!)
            
            // 获取用户的个人信息
            print(userAcount)
            self.loadUserInfo(userAcount, callBack: callBack)
        }
    }
    
    
    // 获取用户的个人信息
    private func loadUserInfo(acount: RTUserAcount,callBack:(isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        guard let accessToken = acount.access_token,uid = acount.uid else {
            
            print("请求参数不够")
            callBack(isSuccess: false)
            return
        }
        
        
        let parameters = [
            
            "access_token": accessToken,
            "uid": uid
        ]
        
        HMNetworkTools.sharedTools.requst(.GET, urlString: urlString, parameters: parameters) { (responseObject, error) -> () in
            
            if error != nil {
                callBack(isSuccess: false)
                print(error)
                
                return
            }
            
            acount.screen_name = responseObject!["screen_name"] as? String
            acount.avatar_large = responseObject!["avatar_large"] as? String
            
            // 存储数据
            self.saveUserAcount(acount)
            
            
            // 登录成功
            callBack(isSuccess: true)
        }
        
    }
    
    // 归档与解档路径
    private let archiveFile = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("archiveFile")
    
    
    
    // 存储数据
    private func saveUserAcount(acount: RTUserAcount) {
        
        NSKeyedArchiver.archiveRootObject(acount, toFile: archiveFile)
        
    }
    
    
    // 读取数据
    private func loadUserAcount()->RTUserAcount? {
        
        return (NSKeyedUnarchiver.unarchiveObjectWithFile(archiveFile) as? RTUserAcount)
    }

    
}
